package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdLoginDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
*
*/
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Override
    public ResponseResult login(AdLoginDto dto) {
        if(dto==null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if(adUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //比对密码
        String password = MD5Utils.encodeWithSalt(dto.getPassword(), adUser.getSalt());
        if(!password.equals(adUser.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        String token = AppJwtUtil.getToken(adUser.getId().longValue());

        HashMap<String, Object> result = new HashMap<>();
        adUser.setPassword("");
        adUser.setSalt("");
        result.put("token", token);
        result.put("user", adUser);

        return ResponseResult.okResult(result);
    }
}
